{% extends 'base.html' %}
{% block title %}{{ p.title }} · 玉器官网{% endblock %}
{% block content %}

{# 组装所有图片：封面 + 明细图（按 sort_order） #}
{% set _imgs = [] %}
{% if p.cover_image %}
  {% set _junk = _imgs.append(p.cover_image|to_public) %}
{% endif %}
{% for img in p.images|sort(attribute='sort_order') %}
  {% if img.image_path %}
    {% set _junk = _imgs.append(img.image_path|to_public) %}
  {% endif %}
{% endfor %}

<section class="max-w-6xl mx-auto px-4 py-10 grid md:grid-cols-12 gap-8">
  <!-- 左侧：缩略图栏 -->
  <aside class="md:col-span-2 order-2 md:order-1">
    <div id="thumbList" class="flex md:flex-col gap-3 md:gap-3 overflow-auto md:overflow-y-auto max-h-[560px] pr-1">
      {% for src in _imgs %}
      <button
        class="thumb relative ring-2 ring-transparent rounded-lg overflow-hidden focus:outline-none"
        data-index="{{ loop.index0 }}"
        aria-label="thumb {{ loop.index0 }}"
      >
        <img src="{{ src }}" alt="thumb-{{ loop.index0 }}" class="w-20 h-20 md:w-full md:h-auto aspect-square object-cover" />
      </button>
      {% endfor %}
    </div>
  </aside>

  <!-- 中间：主图展示 -->
  <div class="md:col-span-6 order-1 md:order-2">
    <div id="viewer" class="relative rounded-xl overflow-hidden shadow bg-white">
      <img id="mainImage"
           src="{{ _imgs[0] if _imgs else '' }}"
           alt="{{ p.t('title', (get_locale()|string)) or p.title }}"
           class="w-full max-h-[560px] object-contain select-none"
           draggable="false" />

      <div id="zoomLens" class="hidden absolute pointer-events-none"></div>
      <!-- 左右箭头 -->
      <button id="prevBtn"
              class="absolute left-2 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/80 hover:bg-white shadow flex items-center justify-center"
              aria-label="prev">&#8249;</button>
      <button id="nextBtn"
              class="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/80 hover:bg-white shadow flex items-center justify-center"
              aria-label="next">&#8250;</button>
    </div>
  </div>

  <!-- 右侧：商品信息 -->
  <div class="md:col-span-4 order-3">
    <h1 class="text-2xl font-semibold">{{ p.t('title', (get_locale()|string)) }}</h1>
    {% if p.t('subtitle', (get_locale()|string)) %}
      <p class="text-gray-500 mt-1">{{ p.t('subtitle', (get_locale()|string)) }}</p>
    {% endif %}

    {% if p.price %}
      <p class="text-emerald-700 text-xl mt-3">{{ p.price|fmt_price(p.currency) }}</p>
    {% endif %}

    <div class="mt-4 space-y-1 text-sm text-gray-700">
      {% if p.material %}
        <p>{{ _('材质：') }}{{ p.t('material', (get_locale()|string)) }}</p>
      {% endif %}
      {% if p.size_length or p.size_width or p.size_height %}
        <p>
          {{ _('尺寸：') }}
          {{ p.size_length|int_if_whole }}
          {% if p.size_width %}*{{ p.size_width|int_if_whole }}{% endif %}
          {% if p.size_height %}*{{ p.size_height|int_if_whole }}{% endif %}
          {% if p.size_unit %} {{ p.size_unit }}{% endif %}
        </p>
      {% endif %}
      {% if p.weight_value %}
        <p>
          {{ _('重量：') }}{{ p.weight_value }}{% if p.weight_unit %} {{ p.weight_unit }}{% endif %}
        </p>
      {% endif %}
      {% if p.sku %}
        <p>{{ _('编号：') }}{{ p.sku }}</p>
      {% endif %}
      <p>{{ _('是否带认证证书：') }}{{ _('是') if p.has_certificate else _('否') }}</p>

      <p class="text-sm text-gray-600 mt-2">
      {{ _('起订量：') }}<span class="font-semibold">{{ p.min_order_qty or 1 }}</span>  {{ _('件') }}
      </p>
    </div>

    {% set desc = p.t('description', (get_locale()|string)) %}
    {% if desc %}
      <div class="prose max-w-none mt-6">{{ desc|safe }}</div>
    {% endif %}
    <input
      type="number"
      name="qty"
      id="qty-input"
      value="{{ p.min_order_qty or 1 }}"
      min="{{ p.min_order_qty or 1 }}"
      step="1"
      class="border rounded-md px-3 py-2 w-24"
    />
    <!-- 购买/联系 按钮区（联系时携带标题和编号，便于自动生成询盘文案） -->
    <div class="mt-6 flex gap-3">
      {% if p.stock is not none and p.stock <= 0 %}
        {# 库存为 0：不允许直接购买，显示已售罄/联系 #}
        <button class="px-4 py-2 rounded bg-slate-200 text-slate-500 cursor-not-allowed" disabled>
          {{ _('已售罄') }}
        </button>
        <a href="{{ url_for('front.contact') }}?product={{ p.id }}&title={{ (p.t('title', (get_locale()|string)) or p.title)|urlencode }}{% if p.sku %}&sku={{ p.sku|urlencode }}{% endif %}"
          class="px-4 py-2 rounded border border-emerald-600 text-emerald-700 hover:bg-emerald-50">
          {{ _('联系我们购买') }}
        </a>
      {% else %}
        {# 有库存：保持原有逻辑 #}
        {% if p.can_direct_pay %}
          <a href="{{ url_for('front.track_buy_click',
                  pid=p.id, ch='direct',
                  next=url_for('front.checkout', pid=p.id)) }}"
             class="px-4 py-2 rounded border border-emerald-600 text-emerald-700 hover:bg-emerald-50">
            {{ _('立即购买') }}
          </a>
        {% else %}
          <a href="{{ url_for('front.contact') }}?product={{ p.id }}&title={{ (p.t('title', (get_locale()|string)) or p.title)|urlencode }}{% if p.sku %}&sku={{ p.sku|urlencode }}{% endif %}"
             class="px-4 py-2 rounded border border-emerald-600 text-emerald-700 hover:bg-emerald-50">
            {{ _('联系我们购买') }}
          </a>
        {% endif %}
      {% endif %}
    </div>
  </div>
</section>

<script>
(function(){
  const imgs = [
    {% for src in _imgs %}"{{ src }}"{% if not loop.last %},{% endif %}{% endfor %}
  ];
  if (!imgs.length) return;

  let idx = 0;
  const mainImage = document.getElementById('mainImage');
  const thumbs = Array.from(document.querySelectorAll('#thumbList .thumb'));
  const prevBtn = document.getElementById('prevBtn');
  const nextBtn = document.getElementById('nextBtn');

  const qtyInput = document.getElementById('qty-input');
  const minQty = {{ p.min_order_qty or 1 }};
  qtyInput.addEventListener('change', function () {
    let v = parseInt(this.value, 10) || minQty;
    if (v < minQty) v = minQty;
    if (v <= 0) v = minQty;
    this.value = v;
  });

  function setActive(i){
    idx = (i + imgs.length) % imgs.length;
    mainImage.src = imgs[idx];
    thumbs.forEach((el, j) => el.classList.toggle('ring-emerald-500', j === idx));
    const active = thumbs[idx];
    active && active.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
  }

  // 初始化
  setActive(0);

  // 缩略图点击
  thumbs.forEach(btn=>{
    btn.addEventListener('click', () => setActive(parseInt(btn.dataset.index || '0', 10)));
  });

  // 箭头
  prevBtn.addEventListener('click', () => setActive(idx - 1));
  nextBtn.addEventListener('click', () => setActive(idx + 1));

  // 键盘切图
  window.addEventListener('keydown', (e)=>{
    if (['ArrowLeft','ArrowUp'].includes(e.key)) setActive(idx - 1);
    if (['ArrowRight','ArrowDown'].includes(e.key)) setActive(idx + 1);
  });

  // 点击大图新标签查看原图
  mainImage.addEventListener('click', ()=> window.open(imgs[idx], '_blank'));
})();
</script>
{% endblock %}
